package com.peng.sell.service.impl;

import com.peng.sell.converter.OrderMaster2OrderDTOConverter;
import com.peng.sell.dataobject.OrderDetail;
import com.peng.sell.dataobject.OrderMaster;
import com.peng.sell.dataobject.ProductInfo;
import com.peng.sell.dto.CartDTO;
import com.peng.sell.dto.OrderDTO;
import com.peng.sell.enums.OrderStatusEnum;
import com.peng.sell.enums.PayStatusEnum;
import com.peng.sell.enums.ResponseCodeEnum;
import com.peng.sell.exception.SellException;
import com.peng.sell.repository.OrderDetailRepository;
import com.peng.sell.repository.OrderMasterRepository;
import com.peng.sell.service.*;
import com.peng.sell.utils.BigDecimalUtil;
import com.peng.sell.utils.KeyUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.List;
import java.util.stream.Collectors;
@Service
@Slf4j
public class OrderServiceImpl implements OrderService {

    @Autowired
    OrderMasterRepository orderMasterRepository;

    @Autowired
    OrderDetailRepository orderDetailRepository;

    @Autowired
    ProductInfoService productInfoService;

    @Autowired
    PayService payService;

    @Autowired
    SendMessageService sendMessageService;

    @Autowired
    WebSocket webSocket;


    @Override
    @Transactional
    public OrderDTO create(OrderDTO orderDTO) {
        String orderId = KeyUtil.getUUID();
        BigDecimal orderAmount = new BigDecimal(new BigInteger("0"));
        for (OrderDetail orderDetail : orderDTO.getOrderDetailList()){
            ProductInfo product = productInfoService.findOne(orderDetail.getProductId());
            if(product==null){
                throw new SellException(ResponseCodeEnum.PRODUCT_NOT_EXIST);
            }
            //计算订单总价
            orderAmount = orderAmount.add(BigDecimalUtil.mul(product.getProductPrice().doubleValue(),orderDetail.getProductQuantity()));
            //生成订单详情数据
            BeanUtils.copyProperties(product,orderDetail);
            orderDetail.setOrderId(orderId);
            orderDetail.setDetailId(KeyUtil.getUUID());
            orderDetailRepository.save(orderDetail);
        }
        //生成订单主表数据
        OrderMaster orderMaster = new OrderMaster();
        orderDTO.setOrderId(orderId);
        BeanUtils.copyProperties(orderDTO,orderMaster);
        orderMaster.setOrderAmount(orderAmount);
        orderMasterRepository.save(orderMaster);

        //减少库存
        List<CartDTO> cartDTOList = orderDTO.getOrderDetailList().stream().map(e->new CartDTO(e.getProductId(),e.getProductQuantity())).collect(Collectors.toList());
        productInfoService.decreaseStock(cartDTOList);

        //向后台推送新订单通知
        webSocket.sendMessage("你有一笔新订单来啦~~~");
        return orderDTO;
    }

    @Override
    public OrderDTO findOne(String orderId) {
        if(StringUtils.isEmpty(orderId)){
            log.error("[查找详情service]参数错误，openid={}，orderId={}",orderId,orderId);
            throw new SellException(ResponseCodeEnum.PARAM_ERROR);
        }
       OrderMaster orderMaster = orderMasterRepository.getOne(orderId);
       if(orderMaster==null){
           throw  new SellException(ResponseCodeEnum.ORDER_NOT_EXIST);
       }
       List<OrderDetail> orderDetailList = orderDetailRepository.findByOrderId(orderId);
       if(orderDetailList==null){
           throw new SellException(ResponseCodeEnum.ORDER_DETAIL_NOT_EXIST);
       }
       OrderDTO orderDTO = new OrderDTO();
       BeanUtils.copyProperties(orderMaster,orderDTO);
       orderDTO.setOrderDetailList(orderDetailList);
        return orderDTO;
    }

    @Override
    public Page<OrderDTO> findList(String buyerOpenid, Pageable pageable) {
        Page<OrderMaster> orderMasterPage = orderMasterRepository.findByBuyerOpenid(buyerOpenid,pageable);
        List<OrderDTO> orderDTOList = OrderMaster2OrderDTOConverter.converterList(orderMasterPage.getContent());
        return new PageImpl<>(orderDTOList,pageable,orderMasterPage.getTotalElements());
    }

    @Override
    @Transactional
    public OrderDTO cancel(OrderDTO orderDTO) {
        //判断订单状态
        if(orderDTO.getOrderStatus()!=OrderStatusEnum.NEW.getCode()){
            log.error("[取消订单]：订单状态错误:orderId:{},status:{}",orderDTO.getOrderId(),orderDTO.getOrderStatus());
            throw new SellException(ResponseCodeEnum.ORDER_STATUS_ERR);
        }
        //修改订单状态
        OrderMaster orderMaster = new OrderMaster();
        orderDTO.setOrderStatus(OrderStatusEnum.CANCEL.getCode());
        BeanUtils.copyProperties(orderDTO,orderMaster);
        OrderMaster updateResult = orderMasterRepository.save(orderMaster);
        if(updateResult==null){
            log.error("[取消订单]：订单更新状态失败:orderId:{},status:{}",orderDTO.getOrderId(),orderDTO.getOrderStatus());
            throw new SellException(ResponseCodeEnum.ORDER_UPDATE_FAILED);
        }
        //更改库存
        List<CartDTO> cartDTOList = orderDTO.getOrderDetailList().stream().map(e->new CartDTO(e.getProductId(),e.getProductQuantity())).collect(Collectors.toList());
        productInfoService.increaseStock(cartDTOList);

        //如果支付了，则退款
        if(orderDTO.getPayStatus()==PayStatusEnum.SUCCESS.getCode()){
            payService.refund(orderDTO);
        }
        return orderDTO;
    }

    @Override
    @Transactional
    public OrderDTO finish(OrderDTO orderDTO) {
        //判断订单状态
        if(orderDTO.getOrderStatus()!=OrderStatusEnum.NEW.getCode()){
            log.error("[完成订单]：订单状态错误:orderId:{},status:{}",orderDTO.getOrderId(),orderDTO.getOrderStatus());
            throw new SellException(ResponseCodeEnum.ORDER_STATUS_ERR);
        }
        //修改订单状态
        OrderMaster orderMaster = new OrderMaster();
        orderDTO.setOrderStatus(OrderStatusEnum.FINISHED.getCode());
        BeanUtils.copyProperties(orderDTO,orderMaster);
        OrderMaster updateResult = orderMasterRepository.save(orderMaster);
        if(updateResult==null){
            log.error("[完成订单]：订单更新状态失败:orderId:{},status:{}",orderDTO.getOrderId(),orderDTO.getOrderStatus());
            throw new SellException(ResponseCodeEnum.ORDER_UPDATE_FAILED);
        }
        sendMessageService.orderStatus(orderDTO);
        return orderDTO;
    }

    @Override
    @Transactional
    public OrderDTO paid(OrderDTO orderDTO) {
        //判断订单状态
        if(orderDTO.getOrderStatus()!=OrderStatusEnum.NEW.getCode()){
            log.error("[支付订单]：订单状态错误:orderId:{},status:{}",orderDTO.getOrderId(),orderDTO.getOrderStatus());
            throw new SellException(ResponseCodeEnum.ORDER_STATUS_ERR);
        }
        //判断支付状态
        if(orderDTO.getPayStatus()!=PayStatusEnum.WAIT.getCode()){
            log.error("[支付订单]：支付状态错误:orderId:{},status:{}",orderDTO.getOrderId(),orderDTO.getOrderStatus());
            throw new SellException(ResponseCodeEnum.ORDER_PAY__FAILED);
        }
        //修改支付状态
        OrderMaster orderMaster = new OrderMaster();
        orderDTO.setPayStatus(PayStatusEnum.SUCCESS.getCode());
        BeanUtils.copyProperties(orderDTO,orderMaster);
        OrderMaster updateResult = orderMasterRepository.save(orderMaster);
        if(updateResult==null){
            log.error("[支付订单]：更新失败:orderId:{},status:{}",orderDTO.getOrderId(),orderDTO.getOrderStatus());
            throw new SellException(ResponseCodeEnum.ORDER_UPDATE_FAILED);
        }
        return orderDTO;
    }

    @Override
    public Page<OrderDTO> findList(Pageable pageable) {
        Page<OrderMaster> orderMasterPage = orderMasterRepository.findAll(pageable);
        List<OrderDTO> orderDTOList = OrderMaster2OrderDTOConverter.converterList(orderMasterPage.getContent());
        return new PageImpl<>(orderDTOList,pageable,orderMasterPage.getTotalElements());
    }

}
